package com.chinasoft.bean.dao;

import com.chinasoft.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentTest {
    InputStream is = null;
    SqlSessionFactory sqlSessionFactory = null;

    SqlSession sqlSession = null ;
    @Before
    public void beforemethod() throws IOException {
        //1.加载配置文件
        is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.获取SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过SqlSessionFactory 获取sqlSession   参数为true -自动提交
        //sqlSession = sqlSessionFactory.openSession(true);
        sqlSession = sqlSessionFactory.openSession();

    }

    @After
    public void end() throws IOException {
        //6.释放资源
        sqlSession.close();
        is.close();
    }


    @Test
    public void delete(){
        Student student = new Student(6);
        sqlSession.delete("StudentMapper.delete",student);
        sqlSession.commit();

    }
    @Test
    public void update(){

        Student student = new Student(6,"lilie",20);
        sqlSession.update("StudentMapper.update",student);
        sqlSession.commit();
    }

    @Test
    public void insert(){

        Student student = new Student(6,"lilie",20);


        sqlSession.insert("StudentMapper.insert",student);

        sqlSession.commit();

    }

    @Test
    public void selectById(){
        Student stu = sqlSession.selectOne("StudentMapper.selectById",3);
        System.out.println("stu = " + stu);

    }


    @Test
    public void selectAll() throws IOException { //返回值必须为空,没有参数 ，是public的；
        //1.加载配置文件
        //InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //InputStream is = StudentTest.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");
        //System.out.println("is = " + is);
        //2.获取SqlSessionFactory
        //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过SqlSessionFactory 获取sqlSession
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //4执行映射文件中的sql语句
        List<Object> list = sqlSession.selectList("StudentMapper.selectAll");

        //5.处理结果
        list.forEach(System.out :: println);



    }




}